package top.bugger168.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.bugger168.base.exception.CourseOnlineException;
import top.bugger168.base.model.PageParams;
import top.bugger168.base.model.PageResult;
import top.bugger168.content.mapper.*;
import top.bugger168.content.model.dto.AddCourseDto;
import top.bugger168.content.model.dto.CourseBaseInfoDto;
import top.bugger168.content.model.dto.EditCourseDto;
import top.bugger168.content.model.dto.QueryCourseParamsDto;
import top.bugger168.content.model.po.*;
import top.bugger168.content.service.CourseBaseInfoService;

import java.time.LocalDateTime;

/**
 * 课程信息业务管理接口实现类
 */
@Service
public class CourseBaseInfoServiceImpl implements CourseBaseInfoService {
    @Autowired
    CourseBaseMapper courseBaseMapper;
    @Autowired
    CourseMarketMapper courseMarketMapper;
    @Autowired
    CourseCategoryMapper courseCategoryMapper;
    @Autowired
    TeachplanMapper teachplanMapper;
    @Autowired
    CourseTeacherMapper courseTeacherMapper;
    @Autowired
    TeachplanMediaMapper teachplanMediaMapper;


    @Override
    public PageResult<CourseBase> queryCourseBaseList(Long companyId,PageParams pageParams, QueryCourseParamsDto queryCourseParamsDto) {
        // 构建查询对象,根据课程名,审核状态和发布状态查询
        LambdaQueryWrapper<CourseBase> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(queryCourseParamsDto.getCourseName()),CourseBase::getName,queryCourseParamsDto.getCourseName())
                .eq(StringUtils.isNotEmpty(queryCourseParamsDto.getAuditStatus()),CourseBase::getAuditStatus, queryCourseParamsDto.getAuditStatus())
                .eq(StringUtils.isNotEmpty(queryCourseParamsDto.getPublishStatus()),CourseBase::getStatus, queryCourseParamsDto.getPublishStatus())
                .eq(CourseBase::getCompanyId,companyId);
        // TODO: 2023/4/29 按照课程发布状态查询
        // TODO: 2023/4/29 根据培训机构id拼装查询条件

        // 查询数据库
        Page<CourseBase> pageResult = courseBaseMapper.selectPage(new Page<CourseBase>(pageParams.getPageNo(), pageParams.getPageSize()),queryWrapper);
        // 将查询结果封装为标准返回类
        return new PageResult<>(pageResult.getRecords(),pageResult.getTotal(),pageParams.getPageNo(),pageParams.getPageSize());
    }

    @Transactional
    @Override
    public CourseBaseInfoDto createCourseBase(Long companyId, AddCourseDto addCourseDto) {
        // 合法性校验StringUtils.isBlank和StringUtils.isNotEmpty的区别就是多加了个空白字符校验
        if(StringUtils.isBlank(addCourseDto.getName())){
            throw new CourseOnlineException("课程名称为空");
        }
        if(StringUtils.isBlank(addCourseDto.getMt())){
            throw new CourseOnlineException("课程分类为空");
        }
        if(StringUtils.isBlank(addCourseDto.getSt())){
            throw new CourseOnlineException("课程分类为空");
        }
        if (StringUtils.isBlank(addCourseDto.getGrade())) {
            throw new CourseOnlineException("课程等级为空");
        }
        if (StringUtils.isBlank(addCourseDto.getTeachmode())) {
            throw new CourseOnlineException("教育模式为空");
        }
        if (StringUtils.isBlank(addCourseDto.getUsers())) {
            throw new CourseOnlineException("适应人群为空");
        }
        if (StringUtils.isBlank(addCourseDto.getCharge())) {
            throw new CourseOnlineException("收费规则为空");
        }

        CourseBase courseBase = new CourseBase();
        // 将填写的信息填充到新建的对象中
        BeanUtils.copyProperties(addCourseDto,courseBase);
        // 设置审核状态,发布状态,机构id和添加时间
        courseBase.setAuditStatus("202002");
        courseBase.setStatus("203001");
        courseBase.setCompanyId(companyId);
        courseBase.setCreateDate(LocalDateTime.now());

        // 插入课程信息表
        int insert = courseBaseMapper.insert(courseBase);
        if(insert<=0){
            throw new CourseOnlineException("新增课程基本信息失败");
        }
        // 保存信息到课程营销信息表
        CourseMarket courseMarket = new CourseMarket();
        BeanUtils.copyProperties(addCourseDto,courseMarket);
        courseMarket.setId(courseBase.getId());
        int i = saveCourseMarket(courseMarket);
        if(i<=0){
            throw new CourseOnlineException("保存课程营销信息失败");
        }

        // 查询课程基本信息和营销信息并返回
        return this.getCourseBaseInfo(courseMarket.getId());
    }

    // 保存课程营销信息,存在则更新
    private int saveCourseMarket(CourseMarket courseMarket){
        // 收费规则
        String charge = courseMarket.getCharge();
        if(StringUtils.isBlank(charge)){
            throw new CourseOnlineException("收费规则没有选择");
        }
        if(charge.equals("201001")){
            if(courseMarket.getPrice()==null || courseMarket.getPrice() <=0){
                throw new CourseOnlineException("收费价格不能为空且必须大于0");
            }
        }
        // 根据id从营销表中查询,没有则添加
        CourseMarket searchCourseMarket = courseMarketMapper.selectById(courseMarket.getId());
        if(searchCourseMarket==null){
            return courseMarketMapper.insert(courseMarket);
        }else{
            BeanUtils.copyProperties(courseMarket,searchCourseMarket);
            searchCourseMarket.setId(courseMarket.getId());
            return courseMarketMapper.updateById(searchCourseMarket);
        }
    }

    // 根据课程id查询课程基本信息,包括基本信息和营销信息
    @Override
    public CourseBaseInfoDto getCourseBaseInfo(long courseId){
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        if(courseBase==null){
            return null;
        }
        CourseMarket courseMarket = courseMarketMapper.selectById(courseId);
        CourseBaseInfoDto courseBaseInfoDto = new CourseBaseInfoDto();
        BeanUtils.copyProperties(courseBase,courseBaseInfoDto);
        if(courseMarket!=null){
            BeanUtils.copyProperties(courseMarket,courseBaseInfoDto);
        }
        // 查询分类名称填充
        courseBaseInfoDto.setStName(courseCategoryMapper.selectById(courseBase.getSt()).getName());
        courseBaseInfoDto.setMtName(courseCategoryMapper.selectById(courseBase.getMt()).getName());

        return courseBaseInfoDto;
    }

    @Transactional
    @Override
    public CourseBaseInfoDto updateCourseBase(Long companyId, EditCourseDto editCourseDto){
        // 先根据id查询到原数据,查不到就抛异常,查到了还要校验机构名是否统一,不允许修改别的机构课程
        Long courseId = editCourseDto.getId();
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        // 校验课程信息
        if(courseBase==null) CourseOnlineException.cast("课程不存在");
        if(!courseBase.getCompanyId().equals(companyId)) CourseOnlineException.cast("本机构只能修改本机构的课程");
        // 填充信息
        BeanUtils.copyProperties(editCourseDto,courseBase);
        courseBase.setChangeDate(LocalDateTime.now());
        // update
        int i = courseBaseMapper.updateById(courseBase);
        if(i <= 0) throw new CourseOnlineException("更新数据失败");
        // 还要更新营销信息数据
        CourseMarket courseMarket = new CourseMarket();
        BeanUtils.copyProperties(editCourseDto,courseMarket);
        saveCourseMarket(courseMarket);
        return this.getCourseBaseInfo(courseId);
    }

    @Transactional
    @Override
    public void removeCourse(long courseId) {
        // 删除课程基本信息和营销信息
        courseBaseMapper.deleteById(courseId);
        courseMarketMapper.deleteById(courseId);
        // 删除课程计划信息和媒体信息
        LambdaQueryWrapper<Teachplan> teachplanQuery = new LambdaQueryWrapper<>();
        teachplanQuery.eq(Teachplan::getCourseId,courseId);
        teachplanMapper.delete(teachplanQuery);
        LambdaQueryWrapper<TeachplanMedia> teachplanMediaQuery = new LambdaQueryWrapper<>();
        teachplanMediaQuery.eq(TeachplanMedia::getCourseId,courseId);
        teachplanMediaMapper.delete(teachplanMediaQuery);
        // 删除教师信息
        LambdaQueryWrapper<CourseTeacher> teacherQueryWrapper = new LambdaQueryWrapper<>();
        teacherQueryWrapper.eq(CourseTeacher::getCourseId,courseId);
        courseTeacherMapper.delete(teacherQueryWrapper);
    }
}
